import preferences from '@ohos.data.preferences';

class PreferencesUtils {
  prefMap: Map<string, preferences.Preferences> = new Map();

  async loadPreference(context, name) {
    try {
      let pref = await preferences.getPreferences(context, name);
      console.log('testTag',`加载Preference[${name}]成功`)
      this.prefMap.set(name, pref);
    } catch (e) {
      console.log('testTag',`加载Preference[${name}]失败`,JSON.stringify(e))
    }
  }

  async putPreferenceValue(name: string, key: string, value: preferences.ValueType) {
    // 判断preference是否初始化
    if (!this.prefMap.has(name)) {
      console.log('testTag',`Preference[${name}]未初始化！`)
      return;
    }
    try {
      let pref = this.prefMap.get(name);
      // 写入数据
      await pref.put(key, value);
      // 刷盘
      await pref.flush();
      console.log('testTag', `保存Preference[${name}.${key} = ${value}]成功`)
    } catch (e) {
      console.log('testTag', `保存Preference[${name}.${key} = ${value}]失败`,JSON.stringify(e))
    }
  }

  async getPreferenceValue(name: string, key: string, defaultValue: preferences.ValueType) {
    // 判断preference是否初始化
    if (!this.prefMap.has(name)) {
      console.log('testTag',`Preference[${name}]未初始化！`)
      return;
    }
    try {
      let pref = this.prefMap.get(name);
      let value = await pref.get(key, defaultValue);
      console.log('testTag', `读取Preference[${name}.${key} = ${value}]成功`)
      return value;
    } catch (e) {
      console.log('testTag', `读取Preference[${name}.${key}}]失败`,JSON.stringify(e))
    }

  }

}
const preferencesUtils = new PreferencesUtils();
export default preferencesUtils as PreferencesUtils;